﻿package cn.bdqn.sp.controller;

import cn.bdqn.sp.pojo.SysUser;
import cn.bdqn.sp.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

//钟志辉
//北大青鸟
// aaaaa
// bbbbb
//朱根发
// 温炽皓
//熊凌霄
//邬达宏
//陈乾龙
@Controller
public class TestController {

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/test")
    public String test(@ModelAttribute("sysUser") SysUser sysUser){
//        SysUser sysUser = new SysUser();
//        sysUser.setAccount("admin");
//        sysUser.setRealname("张三");
//        sysUser.setPassword("123456");
//        sysUser.setBirthday(new Date());
//        sysUser.setAddress("惠州市");
//        sysUser.setPhone("13547896521");
//        model.addAttribute("sysUser",sysUser);
        return "add";
    }

    @PostMapping("/test/add")
    public String add(@Valid SysUser sysUser, BindingResult bindingResult){

        // 如果有错
        if (bindingResult.hasErrors()){
            return "add";
        }

        sysUser.setCreateduserid(1L);
        int rs = sysUserService.addUser(sysUser);
        return "add";
    }


    @RequestMapping("/upload")
    public String toUpload(){
        return "upload";
    }

    @PostMapping("/test/upload")
    public String upload(@RequestParam("picture") MultipartFile picture){
        // 1.创建一个空白文件
        File file = new File("F:\\b.jpg");

        // 2.将上传的图片内容传输到空白文件
        try {
            picture.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 3.跳转到成功页面
        return "upload";
    }


    @PostMapping("/bind")
    public String bind(Date date){
        System.out.println(date);
        return "redirect:/test";
    }

    @InitBinder
    public void initBinder(WebDataBinder dataBinder){
        // 自定义日期转换器
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor editor = new CustomDateEditor(sdf,true);

        // 将自定义日期转换器注册databinder进去
        dataBinder.registerCustomEditor(Date.class,editor);
    }
}
